package com.wingscode.modules.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wingscode.common.utils.PageUtils;
import com.wingscode.common.utils.R;
import com.wingscode.modules.common.entity.AgentEntity;
import com.wingscode.modules.common.entity.CheckLogEntity;
import com.wingscode.modules.common.entity.UserEntity;
import com.wingscode.modules.common.service.AgentService;
import com.wingscode.modules.common.service.CheckLogService;
import com.wingscode.modules.common.service.UserService;
import com.wingscode.modules.sys.controller.AbstractController;
import com.wingscode.modules.sys.entity.AgentApplyEntity;
import com.wingscode.modules.sys.entity.VipLevelEntity;
import com.wingscode.modules.sys.service.AgentApplyService;
import com.wingscode.modules.sys.service.VipLevelService;
import io.swagger.models.auth.In;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 企业
 *
 * @author yan
 */
@RestController
@RequestMapping("/agent")
public class AgentController extends AbstractController {
    @Autowired
    private UserService userService;
    @Autowired
    private AgentService agentService;
    @Autowired
    private CheckLogService checkLogService;
    @Autowired
    private VipLevelService vipLevelService;
    @Autowired
    private AgentApplyService agentApplyService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("admin:agent:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = agentService.getList(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("admin:agent:info")
    public R info(@PathVariable("id") Integer id) {
        AgentEntity agent = agentService.getById(id);
        if (agent != null) {
            // 获得会员等级
            if (agent.getLevel() != null) {
                VipLevelEntity vipLevel = vipLevelService.getById(agent.getLevel());
                if (vipLevel != null)
                    agent.setLevelName(vipLevel.getName());
            }
            // 获得员工账号
            List<UserEntity> userList = userService.getListByAgent(id);
            // 获得审核记录
            List<CheckLogEntity> logList = checkLogService.getListByAgent(id);

            agent.setUserList(userList);
            agent.setCheckLogList(logList);
        }

        return R.ok().put("agent", agent);
    }

//    /**
//     * 保存
//     */
//    @RequestMapping("/save")
//    @RequiresPermissions("admin:agent:save")
//    public R save(@RequestBody AgentEntity agent) {
//        agent.setCreateTime(new Date());
//        agent.setIsOfferPrice(0);
//        agent.setState(0);
//        agentService.save(agent);
//
//        return R.ok();
//    }

    /**
     * 修改
     */
    @RequestMapping("/update")
//    @RequiresPermissions("admin:agent:update")
    public R update(@RequestBody AgentEntity agent) {
        if(agent.getId() == null)
            return R.error("id为空");
        AgentEntity entity = agentService.getById(agent.getId());
        if (entity != null) {
            entity.setLevel(agent.getLevel());
            if (agent.getLevel() != entity.getLevel() && agent.getLevel() > 1) {
                // 修改企业发布次数
                if (agent.getQualNum() != null)
                    agent.setQualNum(getQualDiff(agent.getLevel(), entity.getLevel()) + agent.getQualNum());
                if (agent.getPersonnelNum() != null)
                    agent.setPersonnelNum(getPersonnelDiff(agent.getLevel(), entity.getLevel()) + agent.getPersonnelNum());
            }
            // 非注册企业都可报价，is_offer_price设为1
            if (agent.getLevel() != 1)
                entity.setIsOfferPrice(1);
            entity.setState(agent.getState());
            entity.setUpdateTime(new Date());
            entity.setQualNum(agent.getQualNum());
            entity.setPersonnelNum(agent.getPersonnelNum());
            agentService.updateById(entity);
        }

        return R.ok();
    }

//    /**
//     * 删除
//     */
//    @RequestMapping("/delete")
//    @RequiresPermissions("admin:agent:delete")
//    public R delete(@RequestBody Long[] ids) {
//        userService.removeByIds(Arrays.asList(ids));
//
//        return R.ok();
//    }

    /**
     * 企业审核
     */
    @GetMapping("/check")
    public R check(@RequestParam Integer id, @RequestParam Integer state, @RequestParam String remark) {
        if (id == null)
            return R.error("id为空");
        if (state == null)
            return R.error("state为空");

        AgentEntity agent = agentService.getById(id);
        if (agent != null) {
            agent.setState(state);
            agent.setUpdateTime(new Date());
            agentService.updateById(agent);

            // 添加审核记录
            CheckLogEntity checkLogEntity = new CheckLogEntity();
            checkLogEntity.setCreateTime(new Date());
            checkLogEntity.setUserId(getUserId().intValue());
            checkLogEntity.setRemark(remark);
            checkLogEntity.setState(state);
            checkLogEntity.setType(1);
            checkLogEntity.setAgentId(id);

            checkLogService.save(checkLogEntity);
        }

        return R.ok();
    }

    /**
     * 会员等级下拉框
     */
    @GetMapping("/getVipLevelList")
    public R getVipLevelList() {
        List<VipLevelEntity> list = vipLevelService.list(
                new QueryWrapper<VipLevelEntity>()
                        .eq("state", 1)
                        .eq("pid", 0)
                        .orderByDesc("id")
        );

        return R.ok(200, list);
    }

    /**
     * 会员等级列表
     */
    @GetMapping("getVipLevelPage")
    public R getVipLevelPage(@RequestParam Map<String, Object> params) {
        PageUtils page = vipLevelService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 保存会员等级
     */
    @RequestMapping("/saveVip")
    public R saveVip(@RequestBody VipLevelEntity vipLevelEntity) {
        if (vipLevelEntity.getName().isEmpty())
            return R.error("name为空");

        vipLevelEntity.setPid(0);
        vipLevelEntity.setState(1);
        vipLevelService.save(vipLevelEntity);

        if (vipLevelEntity.getNumList() != null && vipLevelEntity.getNumList().size() > 0) {
            for (VipLevelEntity entity : vipLevelEntity.getNumList()) {
                VipLevelEntity child = new VipLevelEntity();
                child.setPid(vipLevelEntity.getId());
                child.setDicId(entity.getDicId());
                child.setNum(entity.getNum());
                child.setState(1);

                vipLevelService.save(child);
            }
        }

        return R.ok();
    }

    /**
     * 修改会员等级
     */
    @RequestMapping("/updateVip")
    public R updateVip(@RequestBody VipLevelEntity vipLevelEntity) {
        vipLevelEntity.setState(1);
        vipLevelService.updateById(vipLevelEntity);

        // 删除原有关联
        vipLevelService.remove(new QueryWrapper<VipLevelEntity>().eq("pid", vipLevelEntity.getId()));
        // 保存现有关联
        if (vipLevelEntity.getNumList() != null && vipLevelEntity.getNumList().size() > 0) {
            for (VipLevelEntity entity : vipLevelEntity.getNumList()) {
                VipLevelEntity child = new VipLevelEntity();
                child.setPid(vipLevelEntity.getId());
                child.setDicId(entity.getDicId());
                child.setNum(entity.getNum());
                child.setState(1);

                vipLevelService.save(child);
            }
        }

        return R.ok();
    }

    /**
     * 删除会员等级
     */
    @RequestMapping("/deleteVip")
    public R deleteVip(@RequestBody Long[] ids) {
        // 检查会员等级的人数
        if (ids != null && ids.length > 0) {
            for (Long id : ids) {
                List<AgentEntity> agentList = agentService.list(
                        new QueryWrapper<AgentEntity>()
                                .eq("level", id.intValue())
                );

                if (agentList != null && agentList.size() > 0)
                    return R.error("id=" + id.intValue() + "的会员人数大于0，不能删除");
            }
        }

        // 删除会员等级
        vipLevelService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    @GetMapping("vipInfo/{id}")
    public R vipInfo(@PathVariable("id") Integer id) {
        VipLevelEntity vipLevel = vipLevelService.getById(id);
        if (vipLevel != null) {
            List<VipLevelEntity> numList = vipLevelService.numList(vipLevel.getId());
            vipLevel.setNumList(numList);
        }

        return R.ok().put("info", vipLevel);
    }


    /**
     * 申请列表
     */
    @GetMapping("/applyList")
    public R applyList(@RequestParam Map<String, Object> params) {
        PageUtils page = agentApplyService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 渠道用户申请审核
     */
    @GetMapping("/applyCheck")
    public R applyCheck(@RequestParam Integer id, @RequestParam Integer state, @RequestParam String remark) {
        if (id == null)
            return R.error("id为空");
        if (state == null)
            return R.error("state为空");

        AgentApplyEntity entity = agentApplyService.getById(id);
        if (entity != null) {
            entity.setState(state);
            entity.setUpdateTime(new Date());
            agentApplyService.updateById(entity);

            // 添加审核记录
            CheckLogEntity checkLogEntity = new CheckLogEntity();
            checkLogEntity.setCreateTime(new Date());
            checkLogEntity.setUserId(getUserId().intValue());
            checkLogEntity.setRemark(remark);
            checkLogEntity.setState(state);
            checkLogEntity.setType(2);

            checkLogService.save(checkLogEntity);

            // 更新企业渠道申请状态
            AgentEntity agent = agentService.getById(entity.getAgentId());
            if (agent != null) {
                // 审核通过，企业变成渠道用户
                if (state == 1) {
                    agent.setIsOfferPrice(1);
                    agent.setLevel(3);

                    // 修改企业发布次数
                    if (agent.getQualNum() != null)
                        agent.setQualNum(getQualDiff(3, 1) + agent.getQualNum());
                    if (agent.getPersonnelNum() != null)
                        agent.setPersonnelNum(getPersonnelDiff(3, 1) + agent.getPersonnelNum());
                }
                else {
                    agent.setIsOfferPrice(0);
                }
                agent.setUpdateTime(new Date());

                agentService.updateById(agent);
            }
        }

        return R.ok();
    }

    // 获得会员等级企业资质发布次数差值
    // id现有会员等级id，id1原有会员等级id
    private Integer getQualDiff(Integer id, Integer id1) {
        Integer qual = 0, qual1 = 0, diff = 0;
        VipLevelEntity vipLevel = vipLevelService.getById(id);
        if (vipLevel != null) {
            qual = vipLevel.getQualNum() != null ? vipLevel.getQualNum() : 0;
            VipLevelEntity vipLevel1 = vipLevelService.getById(id1);
            if (vipLevel1 != null) {
                if (qual > 0)
                    qual1 = vipLevel1.getQualNum() != null ? vipLevel1.getQualNum() : 0;

                if (qual1 > 0 && qual1 > qual)
                    diff = qual1 - qual;
            }
        }

        return diff;
    }

    // 获得会员等级人才猎聘发布次数差值
    // id现有会员等级id，id1原有会员等级id
    private Integer getPersonnelDiff(Integer id, Integer id1) {
        Integer personnel = 0, personnel1 = 0, diff = 0;
        VipLevelEntity vipLevel = vipLevelService.getById(id);
        if (vipLevel != null) {
            personnel = vipLevel.getPersonnelNum() != null ? vipLevel.getPersonnelNum() : 0;
            VipLevelEntity vipLevel1 = vipLevelService.getById(id1);
            if (vipLevel1 != null) {
                if (personnel > 0)
                    personnel1 = vipLevel1.getPersonnelNum() != null ? vipLevel1.getPersonnelNum() : 0;

                if (personnel1 > 0 && personnel1 > personnel)
                    diff = personnel1 - personnel;
            }
        }

        return diff;
    }
}
